package com.spark.filter;

import com.spark.pojo.User;
import com.spark.utils.Constants;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author zhouqichun
 * @version 1.0
 * @date 2021/8/8 - 08 - 08 - 15:17
 * @description diary com.spark.filter
 */
public class AccessFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = ((HttpServletResponse) servletResponse);
        String path = request.getRequestURI();
        if (path.indexOf("login")>-1){
            filterChain.doFilter(servletRequest,servletResponse);
        }
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(Constants.USER_COOKIE)){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        response.sendRedirect(request.getContextPath()+"/html/login.html");
    }

    @Override
    public void destroy() {

    }
}
